package com.rech.xbexpress3;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.rech.utils.OtherUtil;
import com.sjl.idcard.IdentityCardHandler;
import com.sjl.idcard.entity.IdentityCard;
import com.sjl.idcard.listener.CompoundListener;
import com.sjl.idcard.util.BitmapUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class Kd7Activity extends AppCompatActivity {
    private int jjcount = 100;
    private Timer countTimer;
    private TextView djs ;
    private ImageView iv_front;
    private String m_cardid = "";
    private String m_name = "";
    private static final String TAG = "Kd7Activity";
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;
    private long mLastClickTime = 0;
    public static final long TIME_INTERVAL = 3000L;
    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler();

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar


        }
    };
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
        }
    };
    private boolean mVisible;
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };
    private TextView tv_name;
    private TextView tv_card_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
        String orientation = sharedPreferences.getString("Orientation","");
        if (orientation.equals("landscape")) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        m_name = getIntent().getStringExtra("kd_lj_name");
        m_cardid =  getIntent().getStringExtra("kd_lj_cardid");

        setContentView(R.layout.activity_kd7);
        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mVisible = true;getSupportActionBar().hide();

        //iv_front = findViewById(R.id.iv_front);
        tv_name = findViewById(R.id.tv_name);
        tv_card_id = findViewById(R.id.tv_card_id);
        tv_name.setText(m_name);
        tv_card_id.setText(m_cardid);

        /*ImageView imageView29 = (ImageView)findViewById(R.id.imageView29);
        String cnImage     =  sharedPreferences.getString("CabinetType_gzh","");
        new FetchUrlImageTask(cnImage,imageView29).execute();*/

        Button kd7_jxlj = (Button) findViewById(R.id.kd7_jxlj);
        kd7_jxlj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();

                if (nowTime - mLastClickTime > TIME_INTERVAL) {
                    mLastClickTime = nowTime;
                    Intent intent = new Intent();
                    setResult(4003, intent);
                    Exit();
                    finish();

                }
                //startActivity(new Intent(FullscreenActivity.this, FaceActivity.class));
            }
        });


        Button kd7_cxkg = (Button) findViewById(R.id.kd7_cxkg);
        kd7_cxkg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();

                if (nowTime - mLastClickTime > TIME_INTERVAL) {
                    mLastClickTime = nowTime;
                    SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
                    String obj = sharedPreferences.getString("reopen","");
                    new FetchOpenLocalGridTaskv2ForKD(obj).execute();

                }
                //startActivity(new Intent(FullscreenActivity.this, FaceActivity.class));
            }
        });

        djs = findViewById(R.id.tv_djs);

        TextView kd7_tc = (TextView) findViewById(R.id.tv_back);
        kd7_tc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();

                if (nowTime - mLastClickTime > TIME_INTERVAL) {
                    mLastClickTime = nowTime;
                    Intent intent = new Intent();
                    //intent.putExtra("sn", resultString);
                    setResult(4013, intent);
                    Exit();
                    finish();

                }
                //startActivity(new Intent(FullscreenActivity.this, FaceActivity.class));
            }
        });

        countTimer=new Timer();
        countTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                jjcount--;
                //Jj1Activity.this.djs.setText(String.valueOf(OtherUtil.jjcount));

                Message message = new Message();
                message.what=20000;
                EventBus.getDefault().post(message);
                if(jjcount < 1){
                    //OtherUtil.restartApplication(Jj1Activity.this);
                    Exit();
                    finish();
                }
            }
        },0,1000);

        TextView tv_version = findViewById(R.id.tv_version);
        TextView tv_waiter = findViewById(R.id.tv_waiter);
        try {
            tv_version.setText("v" + OtherUtil.getVersion(this));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String phone = sharedPreferences.getString("CabinetType_phone","");
        tv_waiter.setText("客服电话:" + phone);

        /*IdentityCard identityCard = getIDCardInfo();
        IdentityCardHandler identityCardHandler = IdentityCardHandler.getInstance(this);
        identityCardHandler.compound(identityCard, new CompoundListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(IdentityCard identityCard) {
                Bitmap frontBitmap = identityCard.getFrontBitmap();
                //Bitmap backBitmap = identityCard.getBackBitmap();
//                String frontImageBase64 = identityCard.getFrontImageBase64();
//                String backImageBase64 = identityCard.getBackImageBase64();
                iv_front.setImageBitmap(BitmapUtils.scaleBitmap(frontBitmap, 1.2f));



            }

            @Override
            public void onFailed(Throwable t) {
                Log.e(TAG, "身份证合成失败", t);
            }
        });*/

    }

    /*private IdentityCard getIDCardInfo() {
        //正面
        String name = "宋某某";
        String sex = "男";
        String nation = "汉";
        String birthday = "20200501";
        String address = "福建省厦门市思明区前埔工业园56号";
        String idCardNo = "450981199210150412";
        Bitmap headImg = headImgToBitmap();
        //反面
        String police = "思明区公安局";
        String expiryDate = "2020050120200502";
        IdentityCard identityCard = new IdentityCard(m_name, sex, nation, birthday, address, m_cardid,
                police, expiryDate, headImg);
        return identityCard;
    }*/

    /*private Bitmap headImgToBitmap() {
//        InputStream inputStream = BitmapUtils.openAssets(this, "headdata.txt");
//        String content = readFile(inputStream);
//        byte[] bytes = ByteUtils.hexStringToByteArr(content);
//        Bitmap bitmap = BitmapUtils.byteArrToBitmap(bytes);


        Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.usercard)).getBitmap();
        return bitmap;
    }*/

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mVisible = false;


    }
    private void Exit(){
        EventBus.getDefault().unregister(this);
        //IdentityCardHandler.getInstance(this).release();
    }
    @Override
    protected void onDestroy() {

        super.onDestroy();
    }
    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar
        mVisible = true;


    }

    /**
     * Schedules a call to hide() in delay milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }


    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message){
        Intent intent = new Intent();
        switch(message.what){

            case 10410:
                handleReOpenTask(message.obj);
                break;
            case 10411:
                Toast.makeText(Kd7Activity.this, "重新开柜失败", Toast.LENGTH_SHORT).show();
                break;
            case 20000:
                handleDJS();
                break;
        }
    }
    private void handleDJS(){
        djs.setText(String.valueOf(jjcount));
    }

    public void handleReOpenTask(Object obj) {
        try {
            JSONObject result = new JSONObject(obj.toString());
            if (result.getString("code").equals("100")) {
                View cv = getWindow().getDecorView();
                AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
                adbuilder.setTitle(result.getString("msg"));
                adbuilder.setMessage("2秒后自动关闭！");
                adbuilder.setCancelable(true);
                final AlertDialog dlg = adbuilder.create();
                dlg.show();
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        Intent intent = new Intent();
                        //intent.putExtra("sn", resultString);
                        setResult(4012, intent);
                        t.cancel();
                    }
                }, 2000);

            } else {
                View cv = getWindow().getDecorView();
                AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
                adbuilder.setTitle(result.getString("msg"));
                adbuilder.setMessage("2秒后自动关闭！");
                adbuilder.setCancelable(true);
                final AlertDialog dlg = adbuilder.create();
                dlg.show();
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        dlg.dismiss();
                        t.cancel();
                    }
                }, 2000);

            }

        } catch (Exception e) {
            View cv = getWindow().getDecorView();
            AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
            adbuilder.setTitle("网络异常");
            adbuilder.setMessage("2秒后自动关闭！");
            adbuilder.setCancelable(true);
            final AlertDialog dlg = adbuilder.create();
            dlg.show();
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    dlg.dismiss();
                    t.cancel();
                }
            }, 2000);
        }
    }
}
